package com.xym.sso.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xym.common.util.CookieUtils;
import com.xym.sso.pojo.TaotaoResult;
import com.xym.sso.pojo.User;
import com.xym.sso.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService userService;
	
	private static final String COOKIE_NAME="TT_TOKEN";

	/**
	 * 通用页面跳转
	 * @param pageName
	 * @return
	 */
	@RequestMapping(value = "{pageName}", method = RequestMethod.GET)
	public ModelAndView tpRegister(@PathVariable("pageName")String pageName) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(pageName);
		return modelAndView;
	}
	
	/**
	 * 获取用户登录信息
	 * 
	 */
	@RequestMapping(value="query/{token}",method=RequestMethod.GET)
	public ResponseEntity<User>  queryByToken(@PathVariable("token")String token){
		try {
			User user = userService.queryUserByToken(token);
			
			return ResponseEntity.status(HttpStatus.OK).body(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	}
	

	/**
	 * 检查注册数据
	 * 
	 * @param param
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "check/{param}/{type}", method = RequestMethod.GET)
	public ResponseEntity<Boolean> checkData(
			@PathVariable("param") String param,
			@PathVariable("type") Integer type) {

		try {
			Boolean flag = this.userService.checkData(param, type);
			if (flag == null) {
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
			}
			return ResponseEntity.status(HttpStatus.OK).body(flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
				null);
	}
	
	/**
	 * 登录功能
	 * @param username
	 * @param password
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "doLogin", method = RequestMethod.POST)
	@ResponseBody
	public TaotaoResult doLogin(@RequestParam("username")String username,@RequestParam("password")String password,
			HttpServletRequest request,HttpServletResponse response){
		try {
			String token = userService.login(username,password);
			if(StringUtils.isNotEmpty(token)){
				CookieUtils.setCookie(request, response, COOKIE_NAME, token);
				return  TaotaoResult.ok();
			}
			return TaotaoResult.build(400, "用户名或密码错误");
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return TaotaoResult.build(500, "服务器故障");
	}
	
	
	/**
	 * 注册功能
	 * @param user
	 * @param result
	 * @return
	 */
	@RequestMapping(value = "doRegister", method = RequestMethod.POST)
	public ResponseEntity<TaotaoResult> doRegister(@Valid User user,
			BindingResult result) {
		if (result.hasErrors()) {
			//收集错误信息
			ArrayList<String> list = new ArrayList<String>();
			List<ObjectError> list2 = result.getAllErrors();
			for (ObjectError objectError : list2) {
				list.add(objectError.getDefaultMessage());
			}
			
			return ResponseEntity.status(HttpStatus.OK).body(
					TaotaoResult.build(400, StringUtils.join(list, "|")));
		}
		try {
			Boolean flag = this.userService.registerData(user);
			if (flag == true) {
				return ResponseEntity.status(HttpStatus.OK).body(
						TaotaoResult.ok());
			}
			return ResponseEntity.status(HttpStatus.OK).body(
					TaotaoResult.build(400, "请核对信息后重试"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
				TaotaoResult.build(500, "服务器故障"));
	}
}
